#pragma once

#include <iostream>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <functional>
#include <unordered_map>

#include "log.hpp"
#include "Nocopy.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"
#include "Thread.hpp"
#include "ThreadPool.hpp"
//#include "Task.hpp"

#define Size 1024

static const int default_backlog = 5;

using task_t = std::function<void()>;

// 客户端提供的回调函数
using callback_t = std::function<void(int, InetAddr &addr)>;

// 前置声明先
class TcpServer;

class ThreadData
{
private:
    int _sockfd;
    TcpServer *_tcpserver;
    InetAddr _InetAddr;

public:
    ThreadData(int sockfd, TcpServer *tcpserver, struct sockaddr_in &addr_in) : _sockfd(sockfd), _tcpserver(tcpserver), _InetAddr(addr_in)
    {
    }
    ~ThreadData()
    {
        // 析构自动关闭文件描述符
        close(_sockfd);
    }

    int get_sockfd()
    {
        return _sockfd;
    }

    TcpServer *get_tcp_server()
    {
        return _tcpserver;
    }

    InetAddr &get_addr()
    {
        return _InetAddr;
    }
};

class TcpServer : public nocopy
{
private:
    uint16_t _port;
    int _listen_sockfd;
    bool _isrunning;

    std::unordered_map<std::string, callback_t> funcs;

public:
    TcpServer(uint16_t port) : _port(port)
    {
    }
    ~TcpServer()
    {
        close(_listen_sockfd);
    }

    void Init()
    {
        // 1. 创建套接字
        _listen_sockfd = socket(AF_INET, SOCK_STREAM, 0);
        // AF_INET  ->  IPV4
        // SOCK_STREAM  ->  TCP 协议

        if (_listen_sockfd < 0)
        {
            lg.LogMessage(Fatal, "Create socket error!,errno code: %d,errno string: %s\n", errno, strerror(errno));
            exit(Fatal);
        }
        lg.LogMessage(Debug, "Create socket success,sockfd: %d\n", _listen_sockfd);

        //  解决服务端在主动关闭时,再次启动绑定失败的问题
        int opt = 1; // SOL_SOCKET 在 socket 层
        setsockopt(_listen_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof opt);

        // 2.填充本地网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY); // 0 ???

        // bind

        if (bind(_listen_sockfd, (const sockaddr *)&local, (socklen_t)sizeof local) != 0)
        {
            lg.LogMessage(Fatal, "Bind error!,errno code : %d , error string : %s \n", errno, strerror(errno));
            exit(Fatal);
        }

        lg.LogMessage(Debug, "bind socket success, sockfd: %d\n", _listen_sockfd);

        // Tcp 特有
        if (listen(_listen_sockfd, default_backlog) != 0)
        {
            lg.LogMessage(Fatal, "listen Error!,errno code : %d , error string : %s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
        lg.LogMessage(Debug, "listen socket success, sockfd: %d\n", _listen_sockfd);

        // 创建线程池
        ThreadNs::ThreadPool<task_t>::GetInstance()->Start();
    }

    void Start()
    {
        _isrunning = 1;

        while (_isrunning)
        {
            // accept 返回一个文件描述符
            struct sockaddr_in peer; // 接收一个 sockaddr_in
            socklen_t len = sizeof peer;
            int sockfd = accept(_listen_sockfd, (struct sockaddr *)&peer, &len);

            if (sockfd < 0)
            {
                lg.LogMessage(Warning, "accept socket error,error code: %d , error string : %s\n", sockfd, strerror(errno));

                // Tcp 接收失败不会直接退出，继续接收下一个即可
                continue;
            }

            lg.LogMessage(Debug, "Create socketfd : %d \n", sockfd);

            task_t t = std::bind(&TcpServer::Routine, this, sockfd, InetAddr(peer));
            ThreadNs::ThreadPool<task_t>::GetInstance()->Push(t);
        }
    }

    void RegisterFunc(const std::string &name, callback_t func)
    {
        // 将回调函数和函数名相对应
        funcs[name] = func;
    }

    std::string Read(int sockfd)
    {
        char buffer[Size];
        ssize_t n = read(sockfd, buffer, sizeof buffer - 1);
        if (n > 0)
        {
            buffer[n] = 0;
        }
        else if (n == 0)
        {
            lg.LogMessage(Info, "Client qiut ....\n");
        }
        else
        {
            lg.LogMessage(Error, "Read sockfd error! error code: %d , error string : %s\n", sockfd, strerror(errno));
        }
        return buffer;
    }

    void Routine(int sockfd, InetAddr _inetaddr)
    {
        flag:
        std::string type = Read(sockfd);
        lg.LogMessage(Debug,"%s selet -> %s \n",_inetaddr.PrintDebug().c_str(),type.c_str());
        if (type == "ping")
        {
            funcs["ping"](sockfd,_inetaddr);
        }
        else if(type == "translate")
        {
            funcs["translate"](sockfd,_inetaddr);
        }
        else if(type=="transform")
        {
            funcs["transform"](sockfd,_inetaddr);
        }
        else    // default 
        {
            funcs["default"](sockfd,_inetaddr);
            goto flag;
        }

        // 记得关闭文件描述符
        close(sockfd);
    }

    void Service(int sockfd, InetAddr _inetaddr) // const 修饰的类对象，智能调用类的const函数
    {
    }
};